﻿using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using SixLabors.Fonts.Tables.AdvancedTypographic;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.DbContext;
using SmartPlant.Modules.Base.ViewModels;
using SmartPlant.Services;
using SmartPlant.WinCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Docking;
using Telerik.Windows.Controls.GridView;

namespace SmartPlant.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private DelegateCommand<string> _viewOpenCommand;
        private DelegateCommand<string> _dialogOpenCommand;
        private DelegateCommand<object> _codeChangedCommand;
        private DelegateCommand<object> _viewSelectChangedCommand;
        private DelegateCommand<object> _reSelectDomainCommand;
        private DelegateCommand<object> _viewCloseCommand;
        private DelegateCommand<object> _openLogDirCommand;
        private DelegateCommand<object> _openUnitSelectionCommand;
        private DelegateCommand<object> _tabViewSelectChangedCommand;
        private DelegateCommand<object> _docOpenCommand;
        private DelegateCommand<object> _switchThemeCommand;

        private const string const_title = "Di-Intools";
        private string _title = "Di-Intools";
        private string _moduleName = "";

        private ComboBoxItemModel<SimpleStringModel> _selectedCodelist;
        private ComboBoxItemModel<SimpleStringModel> _SelectedEDE;
        private ComboBoxItemModel<SimpleStringModel> _selectedDocModel;
        private SysInformation _sysInformation;

        private readonly IEventAggregator _eventAggregator = null;
        private readonly IDialogService _dialogService = null;
        private readonly IRegionManager _regionManager = null;

        private const string _viewTableIcon = "&#xe026;";


        public MainWindowViewModel(
            IEventAggregator eventAggregator,
            IRegionManager regionManager,
            IDialogService dialogService)
        {
            _eventAggregator = eventAggregator;
            _dialogService = dialogService;
            _regionManager = regionManager;
            _sysInformation = GlobalObject.SysInformation;
            _eventAggregator.GetEvent<ProjectDomainChangedEvent>().Subscribe(TitleChange);
            InitViewIndexTable();
            InitViewDoc();
            InitCodelists();
            InitQuickFuncList();
            //RadGlyphExtension
        }

        private void InitQuickFuncList()
        {
            QuickFuncList = new List<ComboBoxItemModel<SimpleStringModel>>();
            QuickFuncList.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "删除所有未曾使用过的管线",
                Description = "删除所有未曾使用过的管线",
                IconGlyph = _viewTableIcon,
                IsEnable = true
            });
        }
        private ComboBoxItemModel<SimpleStringModel> _SelectedQuickFunc;

        public ComboBoxItemModel<SimpleStringModel> SelectedQuickFunc
        {
            get { return _SelectedQuickFunc; }
            set { _SelectedQuickFunc = value; }
        }


        /// <summary>
        /// 更换Title。通过事件订阅方式。因为对应事件的定义里就是<see cref="Project"/>类型，<see cref="ProjectDomainChangedEvent"/>
        /// </summary>
        /// <param name="pro"></param>
        private void TitleChange(Project pro)
        {
            if (pro != null)
                this.Title = $"{const_title} - 当前Domian: {pro.ProjName} - 当前Unit： {GlobalObject.CurrentUnit?.UnitName}";
            else
                this.Title = $"{const_title} - 当前Domian: 未打开Domian";
        }
        #region Combox初始化
        private void InitCodelists()
        {
            Codelists.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "仪表类型（Instrument Type）",
                Description = "仪表类型",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "1", v2 = "仪表类型" }
            });
            Codelists.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "仪表状态（Status）",
                Description = "仪表状态",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "361", v2 = "仪表状态" }
            });
            Codelists.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "IO类型（I/O Type）",
                Description = "IO类型",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "376", v2 = "IO类型" }
            });
            Codelists.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "仪表位置（Location）",
                Description = "仪表位置",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = GlobalObject.lookupDic[nameof(ComponentLocation)], v2 = nameof(ComponentLocation) }
            });
            Codelists.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "仪表供货商（Manufacturer）",
                Description = "供货商",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = GlobalObject.lookupDic[nameof(ComponentMfr)], v2 = nameof(ComponentMfr) }
            });
            Codelists.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "仪表型号（Model）",
                Description = "仪表型号",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = GlobalObject.lookupDic[nameof(ComponentMod)], v2 = nameof(ComponentMod) }
            });
        }
        /// <summary>
        /// 一些初始化。此时里面的<see cref="SelectedModel"/>的v1将作为viewName，导航之用
        /// </summary>
        private void InitViewIndexTable()
        {
            IndexViewList.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "未选择视图",
                Description = "未选择视图",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "0", v2 = "" }
            });
            IndexViewList.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "位号默认视图",
                Description = "位号默认视图",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "IndexTable", v2 = "位号默认视图" }
            });
            IndexViewList.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "仪表工艺参数",
                Description = "仪表工艺参数",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "IndexTablePD", v2 = "仪表工艺参数" }
            });
            this.SelectedEDE = IndexViewList[0];
        }
        /// <summary>
        /// 一些初始化
        /// </summary>
        private void InitViewDoc()
        {
            DocComboxList.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "未选择视图",
                Description = "未选择视图",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "0", v2 = "" }
            });
            DocComboxList.Add(new ComboBoxItemModel<SimpleStringModel>
            {
                Name = "默认文档视图",
                Description = "默认文档视图",
                IconGlyph = _viewTableIcon,
                IsEnable = true,
                SelectedModel = new SimpleStringModel { v1 = "DrawingDoc", v2 = "默认文档视图" }
            });
            this.SelectedDoc = DocComboxList[0];
        }
        #endregion


        #region PROP(binding-data)  
        private List<ComboBoxItemModel<SimpleStringModel>> _QuickFuncList;

        public List<ComboBoxItemModel<SimpleStringModel>> QuickFuncList
        {
            get { return _QuickFuncList; }
            set { _QuickFuncList = value; }
        }

        public ComboBoxItemModel<SimpleStringModel> SelectedEDE
        {
            get { return _SelectedEDE; }
            set { SetProperty(ref _SelectedEDE, value); }
        }
        /// <summary>
        /// 选中的下拉列表
        /// </summary>
        public ComboBoxItemModel<SimpleStringModel> SelectedCodelist
        {
            get { return _selectedCodelist; }
            set { SetProperty(ref _selectedCodelist, value); }
        }
        /// <summary>
        /// 系统信息
        /// </summary>
        public SysInformation SysInfo
        {
            get { return _sysInformation; }
            set { SetProperty(ref _sysInformation, value); }
        }

        public ComboBoxItemModel<SimpleStringModel> SelectedDoc
        {
            get { return _selectedDocModel; }
            set { SetProperty(ref _selectedDocModel, value); }
        }
        /// <summary>
        /// 下拉列表管理（下拉）
        /// </summary>
        public List<ComboBoxItemModel<SimpleStringModel>> Codelists { get; set; } = new List<ComboBoxItemModel<SimpleStringModel>>();
        /// <summary>
        /// 索引表的视图选项（下拉）
        /// </summary>
        public List<ComboBoxItemModel<SimpleStringModel>> IndexViewList { get; set; } = new List<ComboBoxItemModel<SimpleStringModel>>();
        public List<ComboBoxItemModel<SimpleStringModel>> DocComboxList { get; set; } = new List<ComboBoxItemModel<SimpleStringModel>>();
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }
        /// <summary>
        /// 绑定了前端，但是在哪里体现呢？
        /// </summary>
        public string ModuleName
        {
            get { return _moduleName; }
            set { SetProperty(ref _moduleName, value); }
        }

        #endregion

        #region Command

        public ICommand ViewCloseCommand
        {
            get
            {
                if (_viewCloseCommand != null) return _viewCloseCommand;
                _viewCloseCommand = new DelegateCommand<object>(onViewCloseCommand);
                return _viewCloseCommand;
            }
        }

        private void onViewCloseCommand(object obj)
        {
            var x = obj.GetType();
            if (x == typeof(DrawingDocViewModel))
            {
                SelectedDoc = DocComboxList[0];
            }
            else if (x == typeof(IndexTableViewModel))
            {
                SelectedEDE = IndexViewList[0];
            }
        }
        private void onViewCloseEvent(SimpleStringModel viewInfo)
        {

        }
        /// <summary>
        /// 重新选择domain按钮后，触发
        /// </summary>
        public ICommand ReSelectDomainCommand
        {
            get
            {
                if (_reSelectDomainCommand != null) return _reSelectDomainCommand;
                _reSelectDomainCommand = new DelegateCommand<object>(onReSelectDomainCommand);
                return _reSelectDomainCommand;
            }
        }
        /// <summary>
        /// 切换主体按钮后，触发
        /// </summary>
        public ICommand SwitchThemeCommand
        {
            get
            {
                if (_switchThemeCommand != null) return _switchThemeCommand;
                _switchThemeCommand = new DelegateCommand<object>(onSwitchThemeommand);
                return _switchThemeCommand;
            }
        }
        /// <summary>
        /// 切换的视图 触发
        /// </summary>
        public ICommand ViewDocSelectChangedCommand
        {
            get
            {
                if (_docOpenCommand != null) return _docOpenCommand;
                _docOpenCommand = new DelegateCommand<object>(onViewSelectChangedCommand);
                return _docOpenCommand;
            }
        }
        /// <summary>
        /// quickbar里的打开日志按钮
        /// </summary>
        public ICommand OpenLogDirCommand
        {
            get
            {
                if (_openLogDirCommand != null) return _openLogDirCommand;
                _openLogDirCommand = new DelegateCommand<object>(onOpenLogDirCommand);
                return _openLogDirCommand;
            }
        }
        /// <summary>
        /// quickbar里的打开pau切换
        /// </summary>
        public ICommand OpenPAUSelectCommand
        {
            get
            {
                if (_openUnitSelectionCommand != null) return _openUnitSelectionCommand;
                _openUnitSelectionCommand = new DelegateCommand<object>(onOpenPAUSelectCommand);
                return _openUnitSelectionCommand;
            }
        }
        /// <summary>
        /// 切换索引表的视图后，触发
        /// </summary>
        public ICommand ViewEDESelectChangedCommand
        {
            get
            {
                if (_viewSelectChangedCommand != null) return _viewSelectChangedCommand;
                _viewSelectChangedCommand = new DelegateCommand<object>(onViewSelectChangedCommand);
                return _viewSelectChangedCommand;
            }
        }
        /// <summary>
        /// 切换<see cref="SelectedCodelist"/>后，触发
        /// </summary>
        public ICommand CodelistChangedCommand
        {
            get
            {
                if (_codeChangedCommand != null) return _codeChangedCommand;
                _codeChangedCommand = new DelegateCommand<object>(onCodelistChangedCommand);
                return _codeChangedCommand;
            }
        }

        /// <summary>
        /// DOCKING里的ActivePaneChanged 绑定
        /// </summary>
        public ICommand TabViewSelectChangedCommand
        {
            get
            {
              if (_tabViewSelectChangedCommand != null) return _tabViewSelectChangedCommand;
                _tabViewSelectChangedCommand = new DelegateCommand<object>(onTabViewSelectChangedCommand);
                return _tabViewSelectChangedCommand;
            }
        }
        /// <summary>
        /// 和前端一些按钮绑定，用于打开视图
        /// </summary>
        public ICommand ViewOpenCommand
        {
            get
            {
                if (_viewOpenCommand != null) return _viewOpenCommand;
                _viewOpenCommand = new DelegateCommand<string>(onViewOpenCommand);
                return _viewOpenCommand;
            }
        }

        /// <summary>
        /// 点击 服务器配置 按钮
        /// </summary>
        public ICommand DialogOpenCommand
        {
            get
            {
                if (_dialogOpenCommand != null) return _dialogOpenCommand;
                _dialogOpenCommand = new DelegateCommand<string>(onDialogOpenCommand);
                return _dialogOpenCommand;
            }
        }
        #endregion



        /// <summary>
        /// 打开日志目录。
        /// </summary>
        /// <param name="obj"></param>
        private void onOpenLogDirCommand(object obj)
        {
            string date = DateTime.Now.ToString("yyyy-MM-dd");
            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"logs\\{date}");
            ExplorerFileExtensions.ExplorerFile(dir);
        }

        /// <summary>
        /// 打开PAU切换
        /// </summary>
        /// <param name="obj"></param>
        private void onOpenPAUSelectCommand(object obj)
        {
            _dialogService.ShowDialog("PAUSelect");
        }

        /// <summary>
        /// 打开视图。
        /// </summary>
        /// <param name="uiParams">委托里有一个string参数，所以可以从xaml的parameter里接受一个参数</param>
        private void onViewOpenCommand(string uiParams)
        {
            string viewName = "";
            string title = "未命名视图";
            string icon = "&#xe025;";
            string[] paramsResult = uiParams.Split(",", System.StringSplitOptions.RemoveEmptyEntries);
            if (paramsResult.Length > 0)
                viewName = paramsResult[0];
            if (paramsResult.Length > 1)
                title = paramsResult[1];
            if (paramsResult.Length > 2)
                icon = paramsResult[2];
            var keyValues = new NavigationParameters
            {
                { "Title", title },
                { "TitleGlyph", icon }
            };
            _regionManager.RequestNavigate(RegionNames.ContentRegion, viewName, keyValues);
            ModuleName = title;
        }

        /// <summary>
        /// 打开对话框。
        /// </summary>
        /// <param name="dialogName"></param>
        private void onDialogOpenCommand(string dialogName)
        {
            _dialogService.ShowDialog(dialogName);
        }
        /// <summary>
        /// 切换主体
        /// </summary>
        /// <param name="obj"></param>
        private void onSwitchThemeommand(object obj)
        {
            _dialogService.Show("SelectTheme");
        }

        /// <summary>
        /// 重新选择工程域。
        /// </summary>
        /// <param name="obj"></param>
        private void onReSelectDomainCommand(object obj)
        {
            _dialogService.Show("DomainSelect", d =>
            {
                if (d.Result == ButtonResult.OK)
                {
                    //重新选择PAU
                    _dialogService.ShowDialog("PAUSelect");
                    //关闭所有已打开的视图。
                    var region = _regionManager.Regions["ContentRegion"];
                    var views = region.Views.Where(t =>
                    {
                        return typeof(ICanClosedDocumentView).IsInstanceOfType(t);
                    }).ToList();

                    foreach (var view in views)
                    {
                        region.Remove(view);
                    }
                    //通知未关闭的视图更新数据。
                    var eventObj = _eventAggregator.GetEvent<ReSelectProjectDomainEvent>();
                    eventObj.Publish(GlobalObject.CurrentProject);
                    //SetTitle();
                }
            });
        }

        /// <summary>
        /// <see cref="SelectedCodelist"/>。
        /// </summary>
        /// <param name="obj"></param>
        private void onCodelistChangedCommand(object obj)
        {
            var eventArgs = obj as SelectionChangedEventArgs;
            if (eventArgs == null) return;
            if (eventArgs.AddedItems.Count < 1) return;
            var selectObj = eventArgs.AddedItems[0] as ComboBoxItemModel<SimpleStringModel>;//得到选中的 
            Console.WriteLine("");

            var par = new Prism.Services.Dialogs.DialogParameters($"{DialogParameterKeys.Id}={selectObj.SelectedModel.v1}&{DialogParameterKeys.Purpose}={selectObj.SelectedModel.v2}&{DialogParameterKeys.Title}={selectObj.Name}");
            
            //c# wpf mvvm prism（对话框）
            
            _dialogService.ShowDialog("CodelistEdit", par,
                P =>
                {
                    SelectedCodelist = null;
                    //回调函数
                });
        }

        /// <summary>
        /// 视图选择发生变更。(EDE DOC)
        /// </summary>
        /// <param name="obj"></param>
        private void onViewSelectChangedCommand(object obj)
        {
            var eventArgs = obj as SelectionChangedEventArgs;
            if (eventArgs == null) return;
            if (eventArgs.AddedItems.Count < 1) return;

            var selectObj = eventArgs.AddedItems[0] as ComboBoxItemModel<SimpleStringModel>;//得到选中的

            if (selectObj != null && !string.IsNullOrEmpty(selectObj.SelectedModel.v1))
            {
                var keyValues = new NavigationParameters
                {
                    { "Title", selectObj.SelectedModel.v2 },
                    { "TitleGlyph", _viewTableIcon}
                };
                ModuleName = selectObj.SelectedModel.v2;
                _regionManager.RequestNavigate(RegionNames.ContentRegion, selectObj.SelectedModel.v1, (e) =>
                {
                    var x = e.Result;

                }, keyValues);


            }
        }



        private void onTabViewSelectChangedCommand(object obj)
        {
            var eventArgs = obj as ActivePangeChangedEventArgs;
            if (eventArgs == null) return;
            if (eventArgs.NewPane == null) return;
            var pane = eventArgs.NewPane as RadDocumentPane;
            if (pane == null) return;
            if (pane.Header == null) return;
            var header = pane.Header as RegionTitle;
            if (header == null)
                ModuleName = pane.Header.ToString();
            else
                ModuleName = header.TitleText;
        }
    }
}
